<template>
  <ElDrawer v-model="drawerVisible" :with-header="false" size="70%">
    <div class="drawer-content">
      <div class="drawer-header">
        <div class="header-left">
          <b>字段管理</b>
          <ElButton style="margin-left: 30px;" type="primary" @click="handleOpenColumnDialog('add')">新增字段</ElButton>
        </div>
        <div class="header-actions">
          <ElButton type="warning" @click="handleGenerateCode">生成</ElButton>
          <ElButton type="danger">预览</ElButton>
          <ElButton>下载</ElButton>
        </div>
      </div>
      <ArtTable rowKey="id" :loading="loading" :data="columns" :columns="tableColumns" size="small" />
    </div>
  </ElDrawer>

  <GenColumnDialog v-model:visible="columnDialogVisible" :type="columnDialogType" :edit-data="currentColumn"
    :business-id="props.businessId" @submit="loadColumns" />
</template>

<script setup lang="ts">
import { fetchGenColumnList, deleteGenColumn, type GenColumn } from '@/api/code_generator/gen_column'
import { generateCode } from '@/api/code_generator/code'
import GenColumnDialog from './gen-column-dialog.vue'
import { useTable } from '@/composables/useTable'
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'


interface Props {
  visible: boolean
  businessId: number
}

interface Emits {
  (e: 'update:visible', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const drawerVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const {
  data: columns,
  getData: loadColumns,
  loading,
  columns: tableColumns
} = useTable({
  core: {
    apiFn: () => fetchGenColumnList(props.businessId),
    immediate: false,
    columnsFactory: () => [
      { prop: 'sort', label: '序号', width: 60 },
      { prop: 'name', label: '名称' },
      {
        prop: 'is_pk',
        label: '是否主键',
        formatter: (row: GenColumn) => h(ElTag, { type: row.is_pk ? 'success' : 'danger' }, () => (row.is_pk ? '是' : '否'))
      },
      { prop: 'comment', label: '描述' },
      { prop: 'type', label: 'SQLA类型' },
      { prop: 'pd_type', label: 'Pydantic类型' },
      { prop: 'default', label: '默认值' },
      { prop: 'length', label: '长度' },
      {
        prop: 'is_nullable',
        label: '是否为空',
        formatter: (row: GenColumn) =>
          h(ElTag, { type: row.is_nullable ? 'success' : 'danger' }, () => (row.is_nullable ? '是' : '否'))
      },
      {
        prop: 'operation',
        label: '操作',
        width: 120,
        formatter: (row: GenColumn) =>
          h('div', [
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => handleOpenColumnDialog('edit', row)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => handleDeleteColumn(row.id)
            })
          ])
      }
    ]
  }
})

const columnDialogVisible = ref(false)
const columnDialogType = ref<'add' | 'edit'>('add')
const currentColumn = ref<GenColumn>()


const handleOpenColumnDialog = (type: 'add' | 'edit', data?: GenColumn) => {
  columnDialogType.value = type
  currentColumn.value = data
  columnDialogVisible.value = true
}

const handleDeleteColumn = (id: number) => {
  ElMessageBox.confirm('确定要删除这个字段吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteGenColumn(id)
      ElMessage.success('删除成功')
      loadColumns()
    } catch (error) {
      console.error('Failed to delete column:', error)
    }
  })
}

const handlePreviewCode = () => {
  ElMessage.info('打开代码预览（待接通后端接口）')
}

const handleGenerateCode = () => {
  if (!props.businessId) {
    ElMessage.warning('请先选择业务')
    return
  }
  // 调用后端代码生成接口
  generateCode(props.businessId)
    .then((paths) => {
      // paths 为生成的逻辑路径列表
      if (Array.isArray(paths) && paths.length > 0) {
        ElMessage.success(`生成成功，共写入 ${paths.length} 个文件`)
        console.log('生成文件列表:', paths)
      } else {
        ElMessage.success('生成成功（无覆盖或无变更）')
      }
    })
    .catch((err) => {
      console.error('生成代码失败:', err)
    })
}

watch(
  () => props.visible,
  (visible) => {
    if (visible && props.businessId) {
      loadColumns()
    }
  }
)
</script>

<style lang="scss" scoped>
.drawer-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
  height: 100%;
}

.drawer-header {
  display: flex;
  gap: 8px;
  align-items: baseline;
  margin-bottom: 8px;
  justify-content: space-between;

  .header-left {
    display: flex;
    gap: 8px;
    align-items: baseline;
  }

  .header-actions {
    display: flex;
    align-items: center;
  }

  .sub {
    color: var(--el-text-color-secondary);
    font-size: 13px;
  }
}
</style>
<style lang="scss" scoped></style>
<style lang="scss">
/* 取消抽屉内部滚动限制 */
.el-drawer__body {
  display: flex;
  flex-direction: column;
}

.el-drawer__body .drawer-content {
  flex: 1;
}
</style>